package com.heima.user.service.Imp;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDTO;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class ApUserLoginServiceImp implements ApUserLoginService {
    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * 用户登录功能
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDTO dto) {
        //0.如果手机号密码登录
        if (StringUtils.isNotEmpty(dto.getPassword()) && StringUtils.isNotEmpty(dto.getPhone())) {
            //1.根据手机号判断用户是否存在
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            //判空
            if (apUser == null) {
                CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"该手机号码还未注册");
            }
            //获得数据库中保存的密码
            String innerPwd = apUser.getPassword();
            //将传入得数据加盐进行Md5算法进行比较
            String typeInPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            //判断密码是否一致
            if (!typeInPwd.equals(innerPwd)) {
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }
            //2.验证通过颁发token
            //2.1创建容器封装需要的响应数据
            HashMap<String, Object> map = new HashMap<>();
            //2.2获得令牌
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            //2.3去除响应前端的相关敏感信息
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("token",token);
            map.put("apUser",apUser);
            return ResponseResult.okResult(map);
        } else {
            //2.使用设备id进行登录
            if (dto.getEquipmentId() == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"设备id不存在");
            }
            //获得token
            String token = AppJwtUtil.getToken(Long.valueOf(dto.getEquipmentId()));
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
